import CommunityCreateModal from '@/components/CommunityCreateModal';
import { getCityList, getCommunityListByCity } from '@/services/city-community';
import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Cascader,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  message,
} from 'antd';
import { useEffect, useState } from 'react';

const { Option } = Select;

interface HouseFormModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  houseId?: string;
}

const HouseFormModal: React.FC<HouseFormModalProps> = ({
  visible,
  onCancel,
  onSuccess,
  houseId,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [createCommunityModalVisible, setCreateCommunityModalVisible] =
    useState(false);

  const [selectedCity, setSelectedCity] = useState<string>('');
  const [communities, setCommunities] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);

  // 加载城市列表
  const loadCities = async () => {
    try {
      const res = await getCityList();
      if (res.success) {
        setCities(res.data);
      }
    } catch (error) {
      console.error('加载城市列表失败:', error);
    }
  };

  // 加载房屋信息
  const loadHouseInfo = async (id: string) => {
    try {
      console.log('加载房屋信息:', id);
      // 这里应该调用实际的API
    } catch (error) {
      console.error('加载房屋信息失败:', error);
    }
  };

  useEffect(() => {
    if (visible) {
      // 加载城市列表
      loadCities();

      // 从props获取房屋ID
      if (houseId) {
        loadHouseInfo(houseId);
      }
    }
  }, [visible, houseId]);

  // 城市选择变化
  const handleCityChange = async (value: (string | number)[]) => {
    if (value && value.length === 2) {
      // 选择了省和市
      const cityValue = String(value[1]); // 取最后一级（市）
      setSelectedCity(cityValue);
      // 清空小区选择
      form.setFieldsValue({ communityId: undefined });

      try {
        // 根据城市加载小区列表
        const res = await getCommunityListByCity(cityValue);
        if (res.success) {
          setCommunities(res.data);
        }
      } catch (error) {
        console.error('加载小区列表失败:', error);
        setCommunities([]);
      }
    } else {
      // 没有选择完整，清空小区列表
      setSelectedCity('');
      setCommunities([]);
      form.setFieldsValue({ communityId: undefined });
    }
  };

  // 处理小区创建成功
  const handleCommunityCreateSuccess = (newCommunity: any) => {
    // 刷新小区列表
    setCommunities([...communities, newCommunity]);
    setCreateCommunityModalVisible(false);
  };

  // 保存房屋信息
  const handleSave = async (values: any) => {
    setLoading(true);
    try {
      console.log('保存房屋信息:', values);
      message.success('房屋信息保存成功');
      onSuccess();
      form.resetFields();
    } catch (error) {
      message.error('保存失败');
      console.error('保存房屋信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setSelectedCity('');
    setCommunities([]);
    onCancel();
  };

  return (
    <>
      <Modal
        title="房屋信息"
        open={visible}
        onCancel={handleCancel}
        onOk={form.submit}
        okText="保存"
        cancelText="取消"
        width={800}
        confirmLoading={loading}
      >
        <Form form={form} layout="vertical" onFinish={handleSave}>
          {/* 1. 城市选择 */}
          <Form.Item
            label="选择城市"
            name="city"
            rules={[{ required: true, message: '请选择城市' }]}
          >
            <Cascader
              placeholder="请选择省/市"
              onChange={handleCityChange}
              options={cities}
              showSearch={{
                filter: (inputValue, path) =>
                  path.some((option) =>
                    option.label
                      .toLowerCase()
                      .includes(inputValue.toLowerCase()),
                  ),
              }}
              displayRender={(labels) => labels[labels.length - 1]}
              changeOnSelect={false} // Only trigger onChange on selecting leaf node
              style={{ width: '100%' }}
            />
          </Form.Item>

          {/* 2. 小区选择 */}
          <Form.Item
            label="选择小区"
            name="communityId"
            rules={[{ required: true, message: '请选择小区' }]}
          >
            <Select
              placeholder={selectedCity ? '请选择小区' : '请先选择城市'}
              disabled={!selectedCity}
              showSearch
              filterOption={(input, option) =>
                String(option?.children ?? '')
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              dropdownRender={(menu) => (
                <>
                  {menu}
                  {selectedCity && communities.length === 0 && (
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                      <p>未找到小区</p>
                      <Button
                        type="link"
                        icon={<PlusOutlined />}
                        onClick={() => setCreateCommunityModalVisible(true)}
                      >
                        创建新小区
                      </Button>
                    </div>
                  )}
                </>
              )}
            >
              {communities.map((community) => (
                <Option key={community.value} value={community.value}>
                  {community.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 3. 房屋基本信息 */}
          <Form.Item
            label="楼栋-房屋号"
            name="buildingHouseNumber"
            rules={[{ required: true, message: '请输入楼栋-房屋号' }]}
          >
            <Input placeholder="如：7栋3单元15层1101" />
          </Form.Item>

          <Form.Item
            label="房屋朝向"
            name="orientation"
            rules={[{ required: true, message: '请选择房屋朝向' }]}
          >
            <Select placeholder="请选择朝向">
              <Option value="north">北</Option>
              <Option value="south">南</Option>
              <Option value="east">东</Option>
              <Option value="west">西</Option>
              <Option value="northeast">东北</Option>
              <Option value="northwest">西北</Option>
              <Option value="southeast">东南</Option>
              <Option value="southwest">西南</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="整套面积"
            name="totalArea"
            rules={[{ required: true, message: '请输入整套面积' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入面积"
              addonAfter="㎡"
              min={0}
              precision={2}
            />
          </Form.Item>

          <Form.Item
            label="户型"
            name="houseLayout"
            rules={[{ required: true, message: '请选择户型' }]}
          >
            <Select placeholder="请选择户型">
              <Option value="1r1l1b">1室1厅1卫</Option>
              <Option value="1r1l2b">1室1厅2卫</Option>
              <Option value="2r1l1b">2室1厅1卫</Option>
              <Option value="2r1l2b">2室1厅2卫</Option>
              <Option value="3r1l1b">3室1厅1卫</Option>
              <Option value="3r1l2b">3室1厅2卫</Option>
              <Option value="3r2l1b">3室2厅1卫</Option>
              <Option value="3r2l2b">3室2厅2卫</Option>
              <Option value="4r1l2b">4室1厅2卫</Option>
              <Option value="4r2l2b">4室2厅2卫</Option>
              <Option value="5r2l2b">5室2厅2卫</Option>
              <Option value="other">其他</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 创建新小区弹窗 */}
      <CommunityCreateModal
        visible={createCommunityModalVisible}
        onCancel={() => setCreateCommunityModalVisible(false)}
        onSuccess={handleCommunityCreateSuccess}
        city={selectedCity}
      />
    </>
  );
};

export default HouseFormModal;
